package com.zhkj.txg.module.home.ui

import android.content.Context
import android.content.Intent
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import com.zhkj.lib.base.ViewModelActivity
import com.zhkj.lib.http.HttpResponseStatus
import com.zhkj.lib.utils.AccountManager
import com.zhkj.txg.R
import com.zhkj.txg.base.CustomApplication
import com.zhkj.txg.base.GlideApp
import com.zhkj.txg.module.home.adapter.EventCommodityAdapter
import com.zhkj.txg.module.home.adapter.RecommendCommodityAdapter
import com.zhkj.txg.module.home.vm.EventCommodityViewModel
import com.zhkj.txg.module.product.ui.ProductDetailActivity2
import com.zhkj.txg.utils.ImageUtils
import kotlinx.android.synthetic.main.activity_event_commodity.*


class EventCommodityActivity : ViewModelActivity<EventCommodityViewModel>() {

    companion object {
        private val TITLE = "title"
        private val TYPE = "type"
        private val ACTIVITY_TYPE = "activityType"
        private val PARAMS = "params"

        fun open(context: Context, title: String, params: Int = 0) {
            val intent = Intent(context, EventCommodityActivity::class.java)
                .putExtra(TITLE, title)
                .putExtra(PARAMS, params)
                .putExtra(TYPE, 0)
            context.startActivity(intent)
        }


        fun openRecommend(context: Context, activityType: Int) {
            val intent = Intent(context, EventCommodityActivity::class.java)
                .putExtra(TYPE, 1)
                .putExtra(ACTIVITY_TYPE, activityType)
            context.startActivity(intent)
        }
    }

    private val eventCommodityAdapter = EventCommodityAdapter()

    private val recommendCommodityAdapter = RecommendCommodityAdapter()

    override fun setViewModel():
            EventCommodityViewModel = createViewModel()

    override val layoutResId: Int
        get() = R.layout.activity_event_commodity

    var openType = 0

    override fun initUI() {

        // 设置TitleBar的高度
        titleEvent.setFragmentStatusBar()

        openType = intent.getIntExtra(TYPE, 0)

        if (openType == 0) {
//            ivEventCommodityImage.visibility = View.VISIBLE
        } else {
            val activityType = intent.getIntExtra(ACTIVITY_TYPE, 0)
            titleEvent.setTitleTextContent(if (activityType == 0) "掌柜推荐" else "限时抢购")
//            ivEventCommodityImage.visibility = View.GONE
        }

        with(rvEventCommodity) {
            layoutManager = LinearLayoutManager(
                this@EventCommodityActivity,
                LinearLayoutManager.VERTICAL,
                false
            )

            if (openType == 0) {
                adapter = eventCommodityAdapter
            } else {
                adapter = recommendCommodityAdapter
            }
        }

        eventCommodityAdapter.setOnItemClickListener { _, _, position ->
            ProductDetailActivity2.normalProduct(
                this,
                eventCommodityAdapter.data[position].id,
                shopId = CustomApplication.getShopId()
            )
        }

        recommendCommodityAdapter.setOnItemClickListener { _, _, position ->
            val entity = recommendCommodityAdapter.data[position]
            ProductDetailActivity2.normalProduct(
                this,
                entity.id,
                shopId = CustomApplication.getShopId()
            )
        }
        eventCommodityAdapter.setOnItemChildClickListener { adapter, view, position ->
            if (view.id == R.id.tvEventAddCart) {
                val map = hashMapOf(
                    "goods_id" to eventCommodityAdapter.data[position].id.toString(),
                    "goods_num" to "1", "shop_id" to CustomApplication.getShopId().toString()
                )
                viewModel.addCart(map)
            }
        }

        refreshCategory.setOnRefreshListener {
            if (openType == 0) {
//                refreshCategory.finishRefresh(false)
                viewModel.getGoodsActivity(AccountManager.getToken(), intent.getIntExtra(PARAMS, 0))
            } else {
                viewModel.searchProduct(intent.getIntExtra(ACTIVITY_TYPE, 0), true)
            }
        }
    }

    override fun initData() {
        if (openType == 0) {
            viewModel.getGoodsActivity(AccountManager.getToken(), intent.getIntExtra(PARAMS, 0))
        } else {
            viewModel.searchProduct(intent.getIntExtra(ACTIVITY_TYPE, 0), true)
        }
    }

    override fun initViewModel() {
        //推荐商品
        viewModel.productListLiveData.observe(this, Observer { response ->
            when (response.status) {
                HttpResponseStatus.Status.START -> Unit
                HttpResponseStatus.Status.SUCCESS -> response.response?.let {
                    // 判断加载状态
                    if (!it.loadMore) refreshCategory.finishRefresh()
                    else if (it.hasMore) recommendCommodityAdapter.loadMoreModule?.loadMoreComplete()
                    else recommendCommodityAdapter.loadMoreModule?.loadMoreEnd()
                    // 数据填充
                    if (it.loadMore) recommendCommodityAdapter.addData(it.data)
                    else recommendCommodityAdapter.setNewData(it.data)
                }
                HttpResponseStatus.Status.FAILURE -> {
                    response.exception?.printStackTrace()
                    toast(response.statusTip)
                    if (viewModel.page > 1) recommendCommodityAdapter.loadMoreModule?.loadMoreFail()
                    else refreshCategory.finishRefresh(false)
                }
            }
        })

        //活动观察者
        viewModel.eventLiveData.observe(this, Observer {
            handlerResponseStatus(it.status, it.statusTip)
            if (it.status == HttpResponseStatus.Status.SUCCESS) {
                it.response?.data?.let { entity ->

                    titleEvent.setTitleTextContent(entity.title)
//                    if (entity.goodsGroup.size == 0) {
//                        ivCommodityImage.visibility = View.VISIBLE
//                        GlideApp.with(this).asDrawable().load(entity.image).into(ivCommodityImage)
//                    } else {
//                        ivCommodityImage.visibility = View.GONE
//                        eventCommodityAdapter.setHeaderView(createHeaderView(entity.image))
//                        eventCommodityAdapter.setNewData(entity.goodsGroup)
//                    }
                    eventCommodityAdapter.setHeaderView(createHeaderView(entity.image))
                    eventCommodityAdapter.setNewData(entity.goodsGroup)
                    refreshCategory.finishRefresh(true)
                }
            }
        })
        // 商品加入购物车观察者
        viewModel.addCartLiveData.observe(this, Observer {
            handlerResponseStatus(it.status, it.statusTip)
            if (it.status == HttpResponseStatus.Status.SUCCESS) {
                toast(getString(R.string.add_cart_success))
            }
        })
    }

    fun createHeaderView(image: String): View {
        return layoutInflater.inflate(R.layout.item_commodity_image, null).apply {
            val ivEventCommodityImage: ImageView = findViewById(R.id.ivEventCommodityImage)
            GlideApp.with(this).asDrawable().load(image).into(ivEventCommodityImage)
        }
    }

}